<?php

namespace app\api\controller\kuerp\third;

use think\Db;
use Exception;
class Customers extends Thirds
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $web_site    = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->web_site = $this->request->server('HTTP_ORIGIN');
    }

    /**
     * 获取职员列表
     * @ApiMethod (POST)
     */
    public function getSalesList()
    {
        $data = input();
        $page = isset($data['page'])?$data['page']:1;
        $page = empty($page)?1:$page;
        $limit = isset($data['limit'])?$data['limit']:10;
        $limit = empty($limit)?10:$limit;

        $where = [];
        $keyword = isset($data['keyword'])?$data['keyword']:'';
        if(!empty($keyword)){
            $where['men_code|name|phone'] = ['like','%'.$keyword.'%'];
        }
        $where['status'] = '1';

        $list = Db::name('kuerp_staff_member')
            ->where($where)
            ->page($page,$limit)
            ->field('id,men_code,name,phone,FROM_UNIXTIME(updatetime,\'%Y-%m-%d %H:%i:%s\') as updatetime')
            ->select();

        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['phone'] = preg_match("/^1[3-9]{1}\d{9}$/",$list_v['phone']) ? substr_replace($list_v['phone'],'****',3,4) : $list_v['phone'];
        }
        $count = Db::name('kuerp_staff_member')->where($where)->count();

        $result['list'] = $list;$result['count'] = $count;
        $this->success('查询成功',$result,200);
    }

    /**
     * 获取客户列表
     * @ApiMethod (POST)
     */
    public function getCustomersList()
    {
        $data = input();
        $page = isset($data['page'])?$data['page']:1;
        $page = empty($page)?1:$page;
        $limit = isset($data['limit'])?$data['limit']:10;
        $limit = empty($limit)?10:$limit;

        $where = [];
        $keyword = isset($data['keyword'])?$data['keyword']:'';
        if(!empty($keyword)){
            $where['customer_code|customer_name|customer_mobile'] = ['like','%'.$keyword.'%'];
        }
        $third_account = $this->third_account;
        $where['third_id'] = $third_account['id'];

        $list = Db::name('kuerp_customers')
            ->where($where)
            ->page($page,$limit)
            ->field('customer_code,customer_name as name,customer_mobile as mobile,staff_member_id as saler,createtime,status')
            ->select();

        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['saler'] = Db::name('kuerp_staff_member')->where(['id'=>$list_v['saler']])->value('men_code');
            $list[$list_k]['createtime_text'] = date('Y-m-d H:i:s',$list_v['createtime']);
        }
        $count = Db::name('kuerp_customers')->where($where)->count();

        $result['list'] = $list;$result['count'] = $count;
        $this->success('查询成功',$result,200);
    }

    /**
     * 添加客户
     * @ApiMethod (POST)
     */
    public function joinCustomers()
    {
        $detail = input();
        $check = $this->checkParameter($detail,[
            'name|客户名称'=>'require',
            'mobile|客户联系方式'=>'require',
        ]);
        if(isset($check['status'])){
            $this->error($check['msg'],'',$check['status']);
        }else{
            $customer_code = $this->getCodes('',1);
            if(empty($customer_code)){
                $this->error('编号获取失败','',27);
            }

            $customer = Db::name('kuerp_customers')
                ->where(['customer_mobile'=>$detail['mobile']])
                ->find();
            if(!empty($customer)){
                $this->error('此手机号已注册','',27);
            }

            //职员信息
            $saler = isset($detail['saler'])?$detail['saler']:'';
            if($saler){
                $saler_info = Db::name('kuerp_staff_member')->where(['men_code'=>$saler,'status'=>'1'])->find();
                if(empty($saler_info)){
                    $this->error('职员不可用','',27);
                }
            }

            //联系人信息
            $data[] = [
                'first_connect_name'    => $detail['name'],
                'first_connect_mobile'  => $detail['mobile'],
                'first_connect_phone'   => '',
                'qq_wx_email'           => '',
                'connect_address'       => isset($detail['address'])?$detail['address']:'',
                'is_first'              => 1,
                'createtime'            => time(),
                'updatetime'            => time(),
            ];

            $customertype = Db::name('kuerp_customertype')->where(['status'=>'1'])->order(['id'=>'DESC'])->value('id');

            $third_account = $this->third_account;
            $customer = [
                'customer_code'     => $customer_code,
                'customertype_id'   => $customertype,
                'customerlevel_id'  => 1,
                'customer_name'     => $detail['name'],
                'connet_name'       => $detail['name'],
                'customer_mobile'   => $detail['mobile'],
                'getgoods_address'  => isset($detail['address'])?$detail['address']:'',
                'note'              => isset($detail['note'])?$detail['note']:'',
                'staff_member_id'   => isset($saler_info)? (isset($saler_info['id'])?$saler_info['id']:0) :0,
                'account_time'      => time(),
                'third_id'          => $third_account['id'],
                'createtime'        => time(),
                'updatetime'        => time(),
            ];

            $result = false;
            Db::startTrans();
            try {

                $result = Db::name('kuerp_customers')->insertGetId($customer);
                $business_type = 5;
                Db::name('kuerp_sales_payment_log')->insert([
                    'customers_id' => $result,
                    'business_type' => $business_type,
                    'bill_time' => $customer['account_time'],
                    'bill_code' => $customer['customer_code'],
                    'give_money' => 0,
                ]);

                foreach ($data as $data_k=>$data_v){
                    $data[$data_k]['customers_code'] = trim($customer['customer_code']);
                    $data[$data_k]['sid'] = $result;
                }
                Db::name('kuerp_customers_user')->insertAll($data);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('添加成功',['id'=>$result,'customer_code'=>$customer_code],1);
            } else {
                $this->error('添加失败','',27);
            }
        }
    }

    /**
     * 客户详情
     * @ApiMethod (POST)
     */
    public function customersInfo()
    {
        $detail = input();
        $check = $this->checkParameter($detail,[
            'mobile|电话'=>'require',
        ]);
        if(isset($check['status'])){
            $this->error($check['msg'],'',$check['status']);
        }else{
            $third_account = $this->third_account;
            $customer = Db::name('kuerp_customers')
                ->where(['customer_mobile'=>$detail['mobile'],'third_id'=>$third_account['id']])
                ->field('customer_code,customer_name as name,customer_mobile as mobile,getgoods_address as address,note,staff_member_id as saler,createtime,status')
                ->find();
            if(empty($customer)){
                $this->error('未找到相关客户','',27);
            }elseif ($customer['status']!=1){
                $this->error('此客户状态异常','',27);
            }

            $customer['saler'] = Db::name('kuerp_staff_member')->where(['id'=>$customer['saler']])->value('men_code');
            $customer['createtime_text'] = date('Y-m-d H:i:s',$customer['createtime']);
            $this->success('查询成功',$customer,1);
        }
    }

    /**
     * 编辑客户
     * @ApiMethod (POST)
     */
    public function editCustomers()
    {
        $detail = input();
        $check = $this->checkParameter($detail,[
            'code|客户编号'=>'require',
            'name|客户名称'=>'require',
            'mobile|客户联系方式'=>'require',
        ]);
        if(isset($check['status'])){
            $this->error($check['msg'],'',$check['status']);
        }else{
            $third_account = $this->third_account;
            $customer = Db::name('kuerp_customers')
                ->where(['customer_code'=>$detail['code'],'third_id'=>$third_account['id']])
                ->find();
            if(empty($customer)){
                $this->error('未找到相关客户','',27);
            }elseif ($customer['status']!=1){
                $this->error('此客户状态异常','',27);
            }

            //职员信息
            $saler = isset($detail['saler'])?$detail['saler']:'';
            if($saler){
                $saler_info = Db::name('kuerp_staff_member')->where(['men_code'=>$saler,'status'=>'1'])->find();
                if(empty($saler_info)){
                    $this->error('职员不可用','',27);
                }
            }

            $address = isset($detail['address'])?$detail['address']:'';
            $where = [];
            $where['customers_code'] = $customer['customer_code'];
            $where['sid'] = $customer['id'];
            $where['first_connect_name'] = $detail['name'];
            $where['first_connect_mobile'] = $detail['mobile'];
            $where['connect_address'] = $address;
            $where['is_first'] = 1;
            $user = Db::name('kuerp_customers_user')->where($where)->find();
            if(empty($user)){
                //联系人信息
                $data[] = [
                    'customers_code'        => $customer['customer_code'],
                    'sid'                   => $customer['id'],
                    'first_connect_name'    => $detail['name'],
                    'first_connect_mobile'  => $detail['mobile'],
                    'first_connect_phone'   => '',
                    'qq_wx_email'           => '',
                    'connect_address'       => isset($detail['address'])?$detail['address']:'',
                    'is_first'              => 1,
                    'createtime'            => time(),
                    'updatetime'            => time(),
                ];
            }

            $customer_data = [
                'customer_name'     => $detail['name'],
                'connet_name'       => $detail['name'],
                'customer_mobile'   => $detail['mobile'],
                'getgoods_address'  => isset($detail['address'])?$detail['address']:'',
                'note'              => isset($detail['note'])?$detail['note']:'',
                'staff_member_id'   => isset($saler_info)? (isset($saler_info['id'])?$saler_info['id']:0) :0,
                'updatetime'        => time(),
            ];

            $result = false;
            Db::startTrans();
            try {

                $result = Db::name('kuerp_customers')->where(['id'=>$customer['id']])->update($customer_data);

                if(isset($data)){
                    Db::name('kuerp_customers_user')->where(['sid'=>$customer['id']])->delete();
                    Db::name('kuerp_customers_user')->insertAll($data);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('编辑成功','',1);
            } else {
                $this->error('编辑失败','',27);
            }
        }
    }

    /**
     * 注销客户
     * @ApiMethod (POST)
     */
    public function delCustomers()
    {
        $detail = input();
        $check = $this->checkParameter($detail,[
            'mobile|电话'=>'require',
        ]);
        if(isset($check['status'])){
            $this->error($check['msg'],'',$check['status']);
        }else{
            $third_account = $this->third_account;
            $customer = Db::name('kuerp_customers')
                ->where(['customer_mobile'=>$detail['mobile'],'third_id'=>$third_account['id']])
                ->find();
            if(empty($customer)){
                $this->error('未找到相关客户','',27);
            }

            $customer_name = isset($customer['customer_name'])?$customer['customer_name']:'客户';
            $customers_id = $customer['id'];
            $order_info = Db::name('kuerp_goods_sales_info')->where(['customers_id'=>$customers_id])->value('id');
            if(!empty($order_info)){
                $this->error($customer_name.'已有业务数据，不可注销','',27);
            }
            $order_info = Db::name('kuerp_goods_sales_exchange_info')->where(['customers_id'=>$customers_id])->value('id');
            if(!empty($order_info)){
                $this->error($customer_name.'已有业务数据，不可注销','',27);
            }
            $order_info = Db::name('kuerp_warehouse')->where(['customers_id'=>$customers_id])->value('id');
            if(!empty($order_info)){
                $this->error($customer_name.'已有业务数据，不可注销','',27);
            }
            $order_info = Db::name('kuerp_writeoff')->where(['customers_id|customers_out_id|customers_enter_id'=>$customers_id])->value('id');
            if(!empty($order_info)){
                $this->error($customer_name.'已有业务数据，不可注销','',27);
            }

            $res = false;
            Db::startTrans();
            try {
                $res = Db::name('kuerp_customers')->where(['id'=>['in',$customers_id]])->delete();
                Db::name('kuerp_customers_user')->where(['sid'=>['in',$customers_id]])->delete();
                Db::name('kuerp_writeoff_source')->where(['customers_id'=>['in',$customers_id],'type'=>3])->delete();
                Db::name('kuerp_sales_payment_log')->where(['bill_code'=>['in',$customer['customer_code']],'business_type'=>['in',[5,6]]])->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage(),'',27);
            }
            if($res){
                $this->success('注销成功','',1);
            }else{
                $this->error('注销失败','',27);
            }
        }
    }

}
